<?php

namespace app\admin\controller;

use think\Exception;
use think\helper\Str;
use app\model\RoutesApi;
use think\facade\Request;
use Sffi\ElementPlus\ElForm;
use Sffi\ElementPlus\ElList;
use app\common\entity\ResponseData;
use Sffi\ElementPlus\entity\Option;
use Sffi\ElementPlus\ElForm\ElInput;
use app\_interface\ResourceInterface;
use Sffi\ElementPlus\ElForm\ElSwitch;
use Sffi\ElementPlus\ElForm\ElTreeSelect;

class Role extends \app\admin\controller\AdminBase implements ResourceInterface
{

    public function list()
    {
        $where = input('where');
        $key = input('query', "");
        $model = \app\model\Role::when(isset($where['name']), fn($query) => $query->scope('name', $where['name']))
            ->when($key, fn($query) => $query->whereLike('name', '%'.$key.'%'))
            ->page(input('page', 1), input('size', 10));
        $count = $model->count();
        $routes = $model->select();
        return ResponseData::success($routes, ['sum' => $count, 'page' => input('page', 1), 'size' => input('size', 10)]);
    }

    public function detail()
    {
        $id = input('id', 0);
        return ResponseData::success(\app\model\Role::with(['routesRelation'])->find($id));
    }

    public function add()
    {
        $data = Request::only(['name', 'status','routes_ids']);
        list($routeIds, $apiIds) = $this->getRoutesIdsAndApiIds($data['all_ids']);
        $role = \app\model\Role::create($data);
        $role->routesRelation()->save(['routes_ids'=>$routeIds, 'routes_api_ids'=>$apiIds]);
        return ResponseData::success($role);
    }

    private function getRoutesIdsAndApiIds($data){
        $routeIds = [];
        $apiIds = [];
        foreach ($data as $id) {
            if(Str::startsWith($id, 'a_')){
                $apiIds[] = (int)substr($id, 2);
            }else{
                $routeIds[] = $id;
            }
        }
        return [$routeIds, $apiIds];
    }

    public function update()
    {
        $id = input('id');
        $role = \app\model\Role::with(['routesRelation'])->find($id);
        list($routeIds, $apiIds) = $this->getRoutesIdsAndApiIds(input('all_ids'));
        $role->routesRelation->routes_ids = $routeIds;
        $role->routesRelation->routes_api_ids = $apiIds;
        $role->routesRelation->save();
        $role->allowField(['name', 'status'])->save(input());
        return ResponseData::success($role);
    }

    public function delete($id)
    {
        $id = input('id');
        if (!$id) {
            throw new Exception('非法请求');
        }
        $res = (new \app\model\Role)->where('id', '=', $id)->delete();
        return ResponseData::success($res);
    }

    public function getListColumns()
    {
        $list = new ElList();
        $statusColumn = new ElList\ElSwitch('状态', 'status', 'status', 1, 0);
        $statusColumn->setWidth(150);
        $list->addColumn(new ElList\ElInput('角色名称', 'name', 'name'))
            ->addColumn(new ElList\Column('创建时间', 'create_time', 'create_time'))
            ->addColumn($statusColumn);
        $list->addSearch(new \Sffi\ElementPlus\ElSearch\ElInput('name','name', '请输入角色名称', 0, 31));
        return ResponseData::success($list->__toArray());
    }

    public function getFormColumns()
    {
        $routes = \app\model\Routes::select();
        $form = new ElForm();
        $routesIdsColumn = new ElTreeSelect('角色菜单', 'all_ids', '请选择该角色的菜单权限');
        $routeArr = [];
        $apis = RoutesApi::where(['need_login' => 1])->where('routes_id', '>', 0)->select();
        $resApis = [];
        foreach ($apis as $key => $api) {
            if(!isset($resApis[$api->routes_id])){
                $resApis[$api->routes_id] = [];
            }
            $resApis[$api->routes_id][] = $api;
        }
        foreach ($routes as $route) {
            if ($route->pid == 0){
                if (isset($routeArr[$route->id])) {
                    $routeArr[$route->id]->setValue($route->id)->setKey($route->name)->setDisabled(!$route->status);
                }else{
                    $routeArr[$route->id] = new Option($route->name, $route->id, !$route->status);
                }
            }else{
                if (!isset($routeArr[$route->pid])) {
                    $routeArr[$route->pid] = new Option('','');
                }
                $option = new Option($route->name, $route->id, !$route->status);
                if(isset($resApis[$route->id])){
                    foreach ($resApis[$route->id] as $key => $api) {
                        $option->addChildren(new Option($api->name, 'a_'.$api->id, !$api->status));
                    }
                }
                $routeArr[$route->pid]->addChildren($option);
            }
        }
        $routesIdsColumn->setSelectOption(array_values($routeArr));
        $form->addColumn(new ElInput('角色名称', 'name', '请填写角色名'))
            ->addColumn(new ElSwitch('角色状态', 'status', 1, 0, '有效', '无效'))
            ->addColumn($routesIdsColumn);
        $rule = [
            'title' => [
                ['require' => true, 'message' => '请填写角色名称', 'trigger' => 'blur'],
            ],
        ];
        return ResponseData::success($form->__toArray(), ['rule' => $rule]);
    }
}